#import "CustomTranslationView.h"
#import <objc/runtime.h>

@interface UIWindow (GestureSupport) <UIGestureRecognizerDelegate>
@property (nonatomic, strong) UILongPressGestureRecognizer *translationGesture;
@end

@implementation UIWindow (GestureSupport)

- (UILongPressGestureRecognizer *)translationGesture {
    return objc_getAssociatedObject(self, @selector(translationGesture));
}

- (void)setTranslationGesture:(UILongPressGestureRecognizer *)gesture {
    objc_setAssociatedObject(self, @selector(translationGesture), gesture, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

@end

@interface UIApplication (KeyWindowExtension)
- (UIWindow *)findKeyWindow;
@end

NSDictionary *translationDict;

BOOL disableTranslation = NO;

NSString *findTranslationFor(NSString *text) {
    // 添加禁用检查
    if (disableTranslation) {
        return text;
    }
    
    if (!text) return nil;
    
    if (translationDict[text]) {
        return translationDict[text];
    }
    
    NSString *trimmed = [text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    if (trimmed.length > 0 && translationDict[trimmed]) {
        return translationDict[trimmed];
    }
    
    __block NSString *result = nil;
    [translationDict enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSString *val, BOOL *stop) {
        if ([text containsString:key]) {
            result = [text stringByReplacingOccurrencesOfString:key withString:val];
            *stop = YES;
        }
    }];
    
    return result;
}

void refreshLocalizationInView(UIView *view) {

    if (disableTranslation) {
        return;
    }
    if ([view isKindOfClass:[UILabel class]]) {
        UILabel *label = (UILabel *)view;
        
        if (label.text) {
            NSString *translated = findTranslationFor(label.text);
            if (translated) {
                label.text = translated;
            }
        }
        
        if (label.attributedText) {
            NSString *plainText = label.attributedText.string;
            NSString *translated = findTranslationFor(plainText);
            if (translated) {
                NSMutableAttributedString *newText = [label.attributedText mutableCopy];
                [newText replaceCharactersInRange:NSMakeRange(0, newText.length) withString:translated];
                label.attributedText = newText;
            }
        }
    }
    else if ([view isKindOfClass:[UIButton class]]) {
        UIButton *button = (UIButton *)view;

        NSArray *states = @[@(UIControlStateNormal), @(UIControlStateHighlighted), @(UIControlStateSelected)];
        for (NSNumber *state in states) {
            UIControlState s = [state unsignedIntegerValue];
            
            NSString *title = [button titleForState:s];
            if (title) {
                NSString *translated = findTranslationFor(title);
                if (translated) {
                    [button setTitle:translated forState:s];
                }
            }
            
            NSAttributedString *attributedTitle = [button attributedTitleForState:s];
            if (attributedTitle) {
                NSString *plainText = attributedTitle.string;
                NSString *translated = findTranslationFor(plainText);
                if (translated) {
                    NSMutableAttributedString *newTitle = [attributedTitle mutableCopy];
                    [newTitle replaceCharactersInRange:NSMakeRange(0, newTitle.length) withString:translated];
                    [button setAttributedTitle:newTitle forState:s];
                }
            }
        }
    }
    
    for (UIView *subview in view.subviews) {
        refreshLocalizationInView(subview);
    }
}

%hook UIWindow

- (void)didAddSubview:(UIView *)subview {
    %orig;
    
    if (!self.translationGesture) {
        UILongPressGestureRecognizer *gesture = [[UILongPressGestureRecognizer alloc] 
                                                initWithTarget:self 
                                                action:@selector(handleTranslationGesture:)];
        gesture.numberOfTouchesRequired = 2; // 双指
        gesture.minimumPressDuration = 0.5;  // 长按秒数
        
        gesture.delegate = (id<UIGestureRecognizerDelegate>)self;
        
        [self addGestureRecognizer:gesture];
        self.translationGesture = gesture;
    }
}

%new
- (void)handleTranslationGesture:(UILongPressGestureRecognizer *)gesture {
    if (gesture.state == UIGestureRecognizerStateBegan) {

        CustomTranslationView *translationView = [[CustomTranslationView alloc] initWithFrame:self.bounds];
        [self addSubview:translationView];
        [translationView show];
    }
}

%new
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return YES;
}

%end

%hook UIApplication

- (void)applicationDidBecomeActive:(UIApplication *)application {
    %orig;
    
    UIWindow *keyWindow = [self findKeyWindow];
    if (keyWindow && !keyWindow.translationGesture) {
        UILongPressGestureRecognizer *gesture = [[UILongPressGestureRecognizer alloc] 
                                                initWithTarget:keyWindow 
                                                action:@selector(handleTranslationGesture:)];
        gesture.numberOfTouchesRequired = 2;
        gesture.minimumPressDuration = 1.0;
        
        gesture.delegate = (id<UIGestureRecognizerDelegate>)keyWindow;
        
        [keyWindow addGestureRecognizer:gesture];
        keyWindow.translationGesture = gesture;
    }
}

%new
- (UIWindow *)findKeyWindow {
    UIWindow *keyWindow = nil;
    
    // iOS 13+ 兼容方法
    if (@available(iOS 13.0, *)) {
        for (UIScene *scene in [UIApplication sharedApplication].connectedScenes) {
            if (scene.activationState == UISceneActivationStateForegroundActive && 
                [scene isKindOfClass:[UIWindowScene class]]) {
                UIWindowScene *windowScene = (UIWindowScene *)scene;
                for (UIWindow *window in windowScene.windows) {
                    if (window.isKeyWindow) {
                        keyWindow = window;
                        break;
                    }
                }
                if (keyWindow) break;
            }
        }
    }
    
    if (!keyWindow) {
        NSArray *windows = [UIApplication sharedApplication].windows;
        for (UIWindow *window in windows) {
            if (window.windowLevel == UIWindowLevelNormal) {
                keyWindow = window;
                break;
            }
        }
    }
    
    if (!keyWindow) {
        keyWindow = [UIApplication sharedApplication].windows.firstObject;
    }
    
    return keyWindow;
}

%end

%ctor {
    // 初始化内置字典
    NSMutableDictionary *builtInDict = [@{
        @"Enable": @"启用",
        @"Close": @"关闭",
    } mutableCopy];

    NSDictionary *customDict = [[NSUserDefaults standardUserDefaults] dictionaryForKey:@"CustomTranslations"];
    if (customDict) {
        [builtInDict addEntriesFromDictionary:customDict];
    }

    translationDict = [builtInDict copy];
}

%hook UILabel

- (void)setText:(NSString *)text {
    NSString *translated = findTranslationFor(text);
    %orig(translated ?: text);
}

- (void)setAttributedText:(NSAttributedString *)attributedText {
    NSString *plainText = attributedText.string;
    NSString *translated = findTranslationFor(plainText);
    
    if (translated) {
        NSMutableAttributedString *newText = [attributedText mutableCopy];
        [newText replaceCharactersInRange:NSMakeRange(0, newText.length) withString:translated];
        %orig(newText);
    } else {
        %orig(attributedText);
    }
}

%end

%hook UIButton

- (void)setTitle:(NSString *)title forState:(UIControlState)state {
    NSString *translated = findTranslationFor(title);
    %orig(translated ?: title, state);
}

- (void)setAttributedTitle:(NSAttributedString *)title forState:(UIControlState)state {
    NSString *plainText = title.string;
    NSString *translated = findTranslationFor(plainText);
    
    if (translated) {
        NSMutableAttributedString *newTitle = [title mutableCopy];
        [newTitle replaceCharactersInRange:NSMakeRange(0, newTitle.length) withString:translated];
        %orig(newTitle, state);
    } else {
        %orig(title, state);
    }
}

%end

%hook UIButtonLabel

- (void)setText:(NSString *)text {
    NSString *translated = findTranslationFor(text);
    %orig(translated ?: text);
}

- (void)setAttributedText:(NSAttributedString *)attributedText {
    NSString *plainText = attributedText.string;
    NSString *translated = findTranslationFor(plainText);
    
    if (translated) {
        NSMutableAttributedString *newText = [attributedText mutableCopy];
        [newText replaceCharactersInRange:NSMakeRange(0, newText.length) withString:translated];
        %orig(newText);
    } else {
        %orig(attributedText);
    }
}

%end

%hook UIViewController

- (void)viewDidAppear:(BOOL)animated {
    %orig;
    refreshLocalizationInView(self.view);
}

%end

%hook UIBarButtonItem

- (void)setTitle:(NSString *)title {
    NSString *translated = findTranslationFor(title);
    %orig(translated ?: title);
}

%end

%hook UINavigationItem

- (void)setTitle:(NSString *)title {
    NSString *translated = findTranslationFor(title);
    %orig(translated ?: title);
}

%end